package blog.utils;

import blog.common.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

@Component
public class IpUtil {

    public String getAddr(String ip) {
        String host = "https://ips.market.alicloudapi.com";  // 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = "/iplocaltion";   // 【2】后缀
        String appcode = "adf966014c104bdea9f0521040a6115a"; // 【3】开通服务后 买家中心-查看AppCode
        String urlSend = host + path + "?ip=" + ip;   // 【5】拼接请求链接
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String res = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json:");
                System.out.print(res);//{"code":100,"message":"success","ip":"61.184.100.9","result":{"en_short":"CN","en_name":"China","nation":"中国","province":"湖北省","city":"黄石市","district":"下陆区","adcode":420204,"lat":30.17384,"lng":114.96118}}
                //对res进行json处理
                JSONObject jsonObject = JSONObject.parseObject(res);
                JSONObject result = jsonObject.getJSONObject("result");
                String nation = result.getString("nation");
                String province = result.getString("province");
                String city = result.getString("city");
                String district = result.getString("district");
                return nation + province + city + district;





            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                    return "AppCode错误";
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                    return "请求的 Method、Path 或者环境错误";
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                    return "参数错误";
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                    return "服务未被授权（或URL和Path不正确）";
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                    return "套餐包次数用完";
                } else if (httpCode == 403 && error.equals("Api Market Subscription quota exhausted")) {
                    System.out.println("套餐包次数用完，请续购套餐");
                    return "套餐包次数用完，请续购套餐";
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                    return "参数名错误 或 其他错误";
                }
            }

        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
            return "URL格式错误";
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
            return "URL地址错误";
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
            // e.printStackTrace();
            System.out.println("其他错误");
            return "其他错误";
        }


    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}




